//
//  AppDelegate+WeixinEx.m
//  MyNewProject
//
//  Created by 王春辉 on 2020/1/15.
//  Copyright © 2020年 sun. All rights reserved.
//

#import "AppDelegate+WeixinEx.h"
#import "WJBaseModel.h"

#pragma mark -- mark 微信支付
#define APP_ID_PAY          @"wx3d52d8bd96a1a950"
#define APP_SECRET_ID_PAY    @"112d9e9596da9a38cf50a90123d3d7e2"
#ifndef UNIVERSAL_LINK_PAY
#define UNIVERSAL_LINK_PAY  @"https://hxapi.yupinyouxuan.com"
#endif

//#pragma mark -- mark 微信登录分享
//#define APP_ID          @"wx96254ec25c575e18"
//#define APP_SECRET_ID    @"bec092536e16fd14b6da40cdd000f561"
//#ifndef UNIVERSAL_LINK
//#define UNIVERSAL_LINK  @"https://www.yupinyouxuan.com/"
//#endif
static void(^wxPayResultBlock)(BOOL);
static void(^wxShareResultBlock)(BOOL);
static void(^wxLoginResultBlock)(NSDictionary *);
@implementation AppDelegate (WeixinEx)
- (void)registerWechatPay {
    [WXApi registerApp:APP_ID_PAY universalLink:UNIVERSAL_LINK_PAY];
    [WXApi startLogByLevel:WXLogLevelNormal logBlock:^(NSString *log) {
        NSLog(@"log : %@", log);
    }];
}
- (BOOL)handleOpenUrl:(NSURL *)url {
    NSString *urlString = [NSString stringWithFormat:@"%@", url];
    if ([urlString containsString:APP_ID_PAY]) {
        return [WXApi handleOpenURL:url delegate:self];
    }else {
        return true;
    }
}
- (BOOL)openUrl:(NSURL *)url {
    NSString *urlString = [NSString stringWithFormat:@"%@", url];
    if ([urlString containsString:APP_ID_PAY]) {
        return [WXApi handleOpenURL:url delegate:self];
    }else {
        return true;
    }
    
}
- (BOOL)continueUserActivity:(NSUserActivity *)userActivity {
    return [WXApi handleOpenUniversalLink:userActivity delegate:self];
}

#pragma mark -- mark WXApiDelegate
/*
 是微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用 sendRsp 返回。在调用 sendRsp 返回时，会切回到微信终端程序界面。
 */
-(void)onReq:(BaseReq *)reqonReq {
    
}
/*
 如果第三方程序向微信发送了 sendReq 的请求，那么 onResp 会被回调。sendReq 请求调用后，会切到微信终端程序界面。
 */
-(void)onResp:(BaseResp *)resp {
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *strMsg,*strTitle = [NSString stringWithFormat:@"支付结果"];
        BOOL result;
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付结果：成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                result = true;
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                result = false;
                break;
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        if (wxPayResultBlock) {
            wxPayResultBlock(result);
        }
    }else if ([resp isKindOfClass:[SendMessageToWXResp class]]){
        // 微信分享成功
        NSString *msg;
        if (resp.errCode == WXSuccess) {
            // 分享成功
            msg = @"分享成功";
        }else {
            // 分享失败
            msg = @"分享失败";
        }
        [[UIApplication sharedApplication].keyWindow makeToast:msg duration:0.5 position:CSToastPositionCenter];
    }else if ([resp isKindOfClass:[SendAuthResp class]]){
        // 微信登陆
        SendAuthResp *res = (SendAuthResp *)resp;
        [AppDelegate getWXUserInfoWithCode:res.code Complete:^(NSDictionary *userInfo) {
            if (wxLoginResultBlock) {
                wxLoginResultBlock(userInfo); }
        }];
    }else {}
}
+ (void)payrequestWithNonceStr:(NSString *)noncestr Package:(NSString *)package Partnerid:(NSString *)partnerid Prepayid:(NSString *)prepayid Timestamp:(NSString *)timestamp Sign:(NSString *)sign Complete:(void(^_Nonnull __strong)(BOOL))complete {
    if (![WXApi isWXAppInstalled]) {
        return; }
    PayReq *request = [[PayReq alloc] init];
    request.timeStamp = [timestamp intValue];
    request.nonceStr = noncestr;
    request.package = package;
    request.partnerId = partnerid;
    request.prepayId = prepayid;
    request.sign = sign;
    wxPayResultBlock = complete;
    [WXApi sendReq:request completion:nil];
}
/// 分享
/// @param shareNum 邀请码
/// @param ptNum 产品id
/// @param isSell 拍买 还是 购买
/// @param complete 回调
+ (void)wxShareWith:(NSString *)shareNum PtNum:(NSString *)ptNum SellOrGoodId:(BOOL)isSell Complete:(void(^_Nonnull __strong)(BOOL))complete {
    if (![WXApi isWXAppInstalled]) {
        return; }
    [WXShareTypeView shareResultBlock:^(NSInteger type) {
        [YQNetworking getWithUrl:@"My/getShareMsg" params:@{} reloginRefreshBlock:^(id response) {
            
        } successBlock:^(id response) {
            WJBaseModel *model = [WJBaseModel modelWithDictionary:response];
            if ([model isSuccess]) {
                NSString *title = response[@"data"][@"title"];
                NSString *des = response[@"data"][@"msg"];
                NSString *imageUrlStr = response[@"data"][@"img"];
                NSString *root = @"http://hxapi.yupinyouxuan.com/index.php/Login/reg_h?";
                NSString *key = isSell ? @"sell_id" : @"good_id";
                NSString *url = [NSString stringWithFormat:@"%@reg_num=%@&%@=%@", root, shareNum, key, ptNum];
                NSURL *imageUrl = [NSURL URLWithString:imageUrlStr];
                NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
                UIImage *image = [UIImage imageWithData:imageData];
                
                WXWebpageObject *ext = [WXWebpageObject object];
                ext.webpageUrl = url;
                
                WXMediaMessage *message = [WXMediaMessage message];
                message.title = title;
                message.description = des;
                message.mediaObject = ext;
                message.messageExt = nil;
                message.messageAction = nil;
                [message setThumbImage:image];
                
                SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                req.bText = false;
                req.message = message;
                if (type == 0) {
                    // 微信好友
                    req.scene = WXSceneSession;
                }else if (type == 1){
                    // 朋友圈
                    req.scene = WXSceneTimeline;
                }else {}
                [WXApi sendReq:req completion:complete];
            }else {
#ifdef DEBUG
                if (DEBUG) {
                    NSLog(@"%@", model.msg);
                }
#endif
            }
        } failBlock:^(NSError *error) {
#ifdef DEBUG
            if (DEBUG) {
                NSLog(@"%@", error.localizedDescription);
            }
#endif
        }];
    }];
}
+ (void)wxLoginComplete:(void(^_Nonnull __strong)(NSDictionary *))complete {
    if (![WXApi isWXAppInstalled]) {
        return; }
    wxLoginResultBlock = complete;
    //构造SendAuthReq结构体
    SendAuthReq* req =[[SendAuthReq alloc ] init ];
    req.scope = @"snsapi_userinfo";
    req.state = @"yupinyouxuan";
    [WXApi sendReq:req completion:nil];
}


#pragma mark -- mark 获取微信用户信息

+ (void)getWXUserInfoWithCode:(NSString *)code Complete:(void(^_Nonnull __strong)(NSDictionary *))complete {
    /*
     appid    是    应用唯一标识，在微信开放平台提交应用审核通过后获得
     secret    是    应用密钥AppSecret，在微信开放平台提交应用审核通过后获得
     code    是    填写第一步获取的code参数
     grant_type    是    填authorization_code
     */
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",APP_ID_PAY,APP_SECRET_ID_PAY,code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data1 = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        if (!data1) {
            return ;
        }
        // 授权成功，获取token、openID字典
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        NSString *access_token = dic[@"access_token"];
        NSString *openid= dic[@"openid"];
        [AppDelegate getUserInfoWithAccessToken:access_token WithOpenid:openid Complete:complete];
        
    });
}
+ (void)getUserInfoWithAccessToken:(NSString *)access_token WithOpenid:(NSString *)openid Complete:(void(^_Nonnull __strong)(NSDictionary *))complete {
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,openid];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            // 获取用户信息失败
            if (!data) {
                return ; }
            // 获取用户信息字典
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //用户信息中没有access_token 我将其添加在字典中
            [dic setValue:access_token forKey:@"token"];
            if (complete) {
                complete(dic); }
        });
    });
}
@end



#pragma mark -- mark 微信分享选择框

@interface WXShareTypeView()

@property (nonatomic, copy) void (^shareTypeResult)(NSInteger type);
@end
@implementation WXShareTypeView
+ (WXShareTypeView *)shareResultBlock:(void(^)(NSInteger type))block {
    WXShareTypeView *shareView = [[WXShareTypeView alloc] initWithFrame:CGRectZero];
    shareView.shareTypeResult = block;
    return shareView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
        [self setupContentView];
        [[UIApplication sharedApplication].keyWindow addSubview:self];
        [self mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(0);
        }];
    }
    return self;
}
- (void)setupContentView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    view.backgroundColor = [UIColor whiteColor];
    [self addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.mas_equalTo(self.mas_bottom).mas_offset(- (140 + SKBottomSafe_Height));
    }];
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 setImage:SKIMAGE_NAMED(@"weiXin") forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    btn1.tag = 520;
    [view addSubview:btn1];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setImage:SKIMAGE_NAMED(@"friendQuan") forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    btn2.tag = 521;
    [view addSubview:btn2];
    
    UILabel *label1 = [[UILabel alloc] init];
    label1.textAlignment = NSTextAlignmentCenter;
    label1.font = SKFONT_SIZE(13);
    label1.text = @"微信";
    [view addSubview:label1];
    
    
    UILabel *label2 = [[UILabel alloc] init];
    label2.textAlignment = NSTextAlignmentCenter;
    label2.font = SKFONT_SIZE(13);
    label2.text = @"朋友圈";
    [view addSubview:label2];
    
    [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(view.mas_centerX).multipliedBy(0.5);
        make.top.mas_offset(17.5);
        make.height.mas_equalTo(45);
        make.width.mas_equalTo(btn1.mas_height);
    }];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(btn1);
        make.top.mas_equalTo(btn1.mas_bottom).mas_offset(4);
    }];
    
    [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(view.mas_centerX).multipliedBy(1.5);
        make.top.mas_offset(17.5);
        make.height.mas_equalTo(45);
        make.width.mas_equalTo(btn1.mas_height);
    }];
    
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(btn2);
        make.top.mas_equalTo(btn2.mas_bottom).mas_offset(4);
    }];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [view addSubview:cancelBtn];
    [cancelBtn addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.mas_offset(0);
        make.top.mas_equalTo(btn2.mas_bottom).mas_offset(20);
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self removeFromSuperview];
}
#pragma mark -- mark EVENT
- (void)cancelButtonClick:(UIButton *)sender {
    [self removeFromSuperview];
}
- (void)buttonClick:(UIButton *)sender {
    if (self.shareTypeResult) {
        self.shareTypeResult(sender.tag - 520);
    }
    [self removeFromSuperview];
}
@end
